//
//  CoreDataManager.m
//  CoreDataLHY
//
//  Created by lhy on 2021/1/8.
//

#import "CoreDataManager.h"

#import "SchoolClass+CoreDataProperties.h"
#import "Student+CoreDataProperties.h"

@interface CoreDataManager ()

@property (strong, nonatomic) NSManagedObjectModel *mom;
@property (strong, nonatomic) NSManagedObject *obj;
@property (strong, nonatomic) NSManagedObjectContext *moc;
@property (strong, nonatomic) NSPersistentStoreCoordinator *psc;

@end

@implementation CoreDataManager

/// 数据库管理 单例
+ (instancetype)sharedCoreDataManager {
    static CoreDataManager *sharedCoreDataManager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedCoreDataManager = [[CoreDataManager alloc] init];
    });
    return sharedCoreDataManager;
}

- (void)insertData:(NSDictionary *)info
           handler:(void(^)(BOOL isSaved, NSError *error))handler {
    
    SchoolClass *classRoom = (SchoolClass *)[self getObjName:@"SchoolClass"];
    classRoom.stuNum = 82;
    classRoom.name = @"1";
    
    
    
    for (int i = 0; i < 3; i++) {
        Student *student = (Student *)[self getObjName:@"Student"];
        
        student.age = 22 + i;
        student.name = @"李浩源";
        student.sex = 1;
        
        [classRoom addMonitorObject:student];
    }
    
    [self.moc insertObject:classRoom];
    
    NSError *error = nil;
    
    if ([self.moc hasChanges]) {
        if ([self.moc save:&error]) {
            NSLog(@"insertData 保存成功");
        } else {
            NSLog(@"insertData 失败");
        }
    }
    
    if (handler) {
        handler([NSString stringWithFormat:@"保存结果：%d", [self.moc save:&error]], nil);
    }
}

- (void)fetchData {
    NSFetchRequest *req = SchoolClass.fetchRequest;
    NSError *error = nil;
    NSArray *retArr = [self.moc executeFetchRequest:req error:&error];
    
    if (error) {
        NSLog(@"%@", error.localizedDescription);
    }
    
    [retArr enumerateObjectsUsingBlock:^(SchoolClass *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSLog(@"%hd", obj.stuNum);
        
        [obj.monitor enumerateObjectsUsingBlock:^(Student * _Nonnull obj, BOOL * _Nonnull stop) {
            NSLog(@"姓名：%@  性别：%d  年龄：%d", obj.name, obj.sex, obj.age);
        }];
    }];
}

/// 删
- (void)deleteData {
    NSFetchRequest *req = SchoolClass.fetchRequest;
    
//    NSFetchRequest *req = Student.fetchRequest;

    NSError *error = nil;
    NSArray *retArr = [self.moc executeFetchRequest:req error:&error];

    if (error) {
        NSLog(@"%@", error.localizedDescription);
    }
    if (retArr.count) {
        [self.moc deleteObject:retArr.firstObject];
        [self.moc save:&error];
    }

    
    
//    [retArr enumerateObjectsUsingBlock:^(Student *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//
//        [self.moc deleteObject:obj];
//
//    }];

    
}
/// 改
- (void)updateData {

}

/// 对象模型
- (NSManagedObjectModel *)mom {
    if (!_mom) {
        _mom = [NSManagedObjectModel mergedModelFromBundles:nil];
    }
    return _mom;
}

/// 获取一个对象
/// @param objName 对象名字
- (NSManagedObject *)getObjName:(NSString *)objName {
    
    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:objName inManagedObjectContext:self.moc];
    
    return object;
}

/// 连接器
- (NSPersistentStoreCoordinator *)psc {
    if (!_psc) {
        
        NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"/LHYCoreData.sqlite"];
        
        NSURL *url = [NSURL fileURLWithPath:dirPath];
        
        NSError *err = nil;
        
        _psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.mom];
        
        //请求自动轻量级迁移
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES],
                                 NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES],
                                 NSInferMappingModelAutomaticallyOption,
                                 nil];
        
        [_psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:&err];
        
        if (err) {
            NSLog(@"Error:  addPersistentStoreWithType: %@", err.localizedDescription);
        }
    }
    return _psc;
}

/// 上下文
- (NSManagedObjectContext *)moc {
    if (!_moc) {
        _moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        _moc.persistentStoreCoordinator = self.psc;
    }
    return _moc;
}


@end

